// License: http://www.codeplex.com/entlibcontrib/Project/License.aspx
// Author: Randy

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using EntLibContrib.Logging.Parser;

#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#endif

namespace EntLibContrib.Logging.UnitTests
{
	[TestClass]
	public class RevolvingBehaviorTest
	{
		private const string configurationFilepath = @"RevolvingBehaviorTest.config";
		[TestMethod]
		public void TestRevolvingBehavior()
		{
			foreach (string createdFileName in GetFiles()) {
				File.Delete(createdFileName);
			}
			LogWriterFactory logWriterFactory =
				new LogWriterFactory(
				new FileConfigurationSource(configurationFilepath));
			LogWriter writer = logWriterFactory.Create();
			LogEntry writeLogEntry = new LogEntry();
			writeLogEntry.Categories.Add("Revolving");

			string m0 = new string('0', 1025);
			writeLogEntry.Message = m0;
			writer.Write(writeLogEntry);
			Assert.AreEqual(1, GetFiles().Length);

			string m1 = new string('1', 1025);
			writeLogEntry.Message = m1;
			writer.Write(writeLogEntry);
			Assert.AreEqual(2, GetFiles().Length);
			Assert.IsTrue(File.ReadAllText(@"LogFolder\Revolving.1.log").Contains(m0));

			string m2 = new string('2', 1025);
			writeLogEntry.Message = m2;
			writer.Write(writeLogEntry);
			Assert.AreEqual(3, GetFiles().Length);
			Assert.IsTrue(File.ReadAllText(@"LogFolder\Revolving.2.log").Contains(m1));

			File.SetLastWriteTime(@"LogFolder\Revolving.1.log", new DateTime(2008, 1, 1));
			string m3 = new string('3', 1025);
			writeLogEntry.Message = m3;
			writer.Write(writeLogEntry);
			Assert.AreEqual(3, GetFiles().Length);
			Assert.IsTrue(File.ReadAllText(@"LogFolder\Revolving.1.log").Contains(m2));
		}
		private string[] GetFiles()
		{
			string[] logFiles = Directory.GetFiles("LogFolder", "Revolving" + "*");
			return logFiles;
		}
	}
}
